package com.hgkj.cloud.base.file;

import java.io.File;

import com.hgkj.cloud.base.util.HttpUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class FileProcess {

	@Value("${fileProcess.fileBaseDir}")
	private String fileBaseDir;
	@Value("${fileProcess.fileBaseUrl}")
	private String fileBaseUrl;

	public String process(String filePath, String dir) throws Exception {
		String fullFilePath = fileBaseDir + dir+"/"
				+ FilenameUtils.getName(filePath);
		String fullFileUrl =  "/" + dir+"/"
				+ FilenameUtils.getName(filePath);

		if (filePath.startsWith("http")) {
			HttpUtil.download(filePath, fullFilePath, 0);
		} else {
			FileUtils.copyFile(new File(filePath), new File(fullFilePath));
		}
		return fullFileUrl;
	}

	//返回数组 第一个代表的是在该服务器上的绝对路径，第二个代表的是可访问的相对url
	public String[] processForArray(String filePath, String dir)throws Exception {

		String[] sa = new String[2];
		String fullFilePath = fileBaseDir + dir+"/"
				+ FilenameUtils.getName(filePath);
		String fullFileUrl =  "/" + dir+"/"
				+ FilenameUtils.getName(filePath);

		if (filePath.startsWith("http")) {
			HttpUtil.download(filePath, fullFilePath, 0);
		} else {
			FileUtils.copyFile(new File(filePath), new File(fullFilePath));
		}
		sa[0] = fullFilePath;
		sa[1] = fullFileUrl;
		return sa;

	}

	public String getFileBaseDir() {
		return fileBaseDir;
	}

	public void setFileBaseDir(String fileBaseDir) {
		this.fileBaseDir = fileBaseDir;
	}

	public String getFileBaseUrl() {
		return fileBaseUrl;
	}

	public void setFileBaseUrl(String fileBaseUrl) {
		this.fileBaseUrl = fileBaseUrl;
	}

}
